package com.lma.crm.page;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;


/**
 * HibernateCallBack实现类，用于分页查询
 * @author lma
 *
 * @param <T> 支持各种类型分页查询
 */
public class PageHibernateCallBack<T> implements HibernateCallback<List<T>>{


	private String hql;
	private Object[] params;
	private int startIndex;
	private int pageSize;
	
	public void setHql(String hql) {
		this.hql = hql;
	}

	public void setParams(Object[] params) {
		this.params = params;
	}

	public void setStartIndex(int startIndex) {
		this.startIndex = startIndex;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	
	public PageHibernateCallBack(String hql, Object[] params, int startIndex, int pageSize) {
		super();
		this.hql = hql;
		this.params = params;
		this.startIndex = startIndex;
		this.pageSize = pageSize;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
		// 通过hql获得Query对象
		Query queryObject = session.createQuery(hql);
		// 参数设值
		if (params != null) {
			for (int i = 0; i < params.length; i++) {
				queryObject.setParameter(i, params[i]);
			}
		}
		// 分页
		queryObject.setFirstResult(startIndex);
		queryObject.setMaxResults(pageSize);
		
		return queryObject.list();
		
	}

}
